import React, { ReactElement, useState, useRef, useEffect, useCallback } from 'react'
import { InputItem, Button } from 'antd-mobile'
import { history } from 'umi'
import styles from './index.less'
interface SearchProps {
    queryList: Function,
    searchTarget: Function
}
/**
 * InputItem, Button from 'antd-mobile'
 * InputItem 
 *  ref={inputRef}
 *  value={input}
 *  onChange={inputChange}
 *  clear 清除按钮
 * Button
 */
export default function searchInput({ queryList, searchTarget }: SearchProps): ReactElement {
    const inputRef = useRef<any>(null)
    const [searching, setsearching] = useState<boolean>(false)
    const [input, setinput] = useState<string>('')
    /** 挂载聚焦 */
    useEffect(() => {
        inputRef.current.focus()
    }, [])
    const inputChange = useCallback(
        (value: string) => {
            setinput(value)
        }, [input])
    const searchHandle = () => {
        if (searching) {
            searchTarget(input)
        } else {
            history.push('/')
        }
    }
    useEffect(() => {
        const val = input.trim()
        setsearching(val !== '')
        console.log('searching', searching);

    }, [input])
    /**
     * value onChange 受控组件
     * ref 为了聚焦
     * clear 显示有数据时右侧的小叉叉
     * 
     */
    return (
        <div className={styles.main}>
            <InputItem
                value={input}
                onChange={inputChange}
                className={styles.searchBar}
                ref={inputRef}
                clear
            ></InputItem>
            <Button
                onClick={searchHandle}
                className={styles.btn}
            >{searching ? '搜索' : '取消'}</Button>
        </div>
    )
}
